import React from 'react'
import styles from '../../assets/style/Login.module.css'
import { Button, Checkbox, Form, Input } from 'antd'
import { login, validate } from '../../request/http.js'
import { useNavigate } from 'react-router-dom'
import { useEffect } from 'react'
import { useSelector, useDispatch } from 'react-redux'

const Login = () => {
  const token = useSelector(state => state.token.value)
  const $dispatch = useDispatch()
  const navigate = useNavigate()
  /* 在组件加载时验证token，模拟Vue中的导航守卫 */
  useEffect(() => {
    validate('/validate').then(res => {
      const { code } = res
      if (code == 0) {
        /*code=0， token有效 则跳转至主页 */
        navigate('/home')
      } else {
        /* 否则 继续留在登录页*/
      }
    })
  }, [])
  /* 表单验证成功触发的事件 */
  const onFinish = values => {
    // console.log('Success:', values)
    const data = { username: values.username, password: values.password }
    login('/login', data).then(res => {
      // console.log(res)
      const { code, token } = res
      if (code == 0) {
        $dispatch({
          type: 'token/setValue',
          value: token,
        })
        navigate('/home')
      }
    })
  }
  /* 表单验证失败触发的事件 */
  const onFinishFailed = errorInfo => {
    console.log('Failed:', errorInfo)
  }
  return (
    <div className={styles.container}>
      <Form
        name="basic"
        labelCol={{
          span: 8,
        }}
        wrapperCol={{
          span: 16,
        }}
        initialValues={{
          remember: true,
        }}
        onFinish={onFinish}
        onFinishFailed={onFinishFailed}
        autoComplete="off"
      >
        <div className={styles.contentcontainer}>
          <div className={styles.formheader}>管理员登录</div>
          <div className={styles.formcontent}>
            <Form.Item
              label="用户名"
              name="username"
              rules={[
                {
                  required: true,
                  message: '请输入管理员用户名',
                },
              ]}
            >
              <Input />
            </Form.Item>
            <Form.Item
              label="密码"
              name="password"
              rules={[
                {
                  required: true,
                  message: '请输入密码!',
                },
              ]}
            >
              <Input.Password />
            </Form.Item>
            <Form.Item
              name="remember"
              valuePropName="checked"
              wrapperCol={{
                offset: 8,
                span: 16,
              }}
            >
              <Checkbox>记住我</Checkbox>
            </Form.Item>

            <Form.Item
              wrapperCol={{
                offset: 8,
                span: 16,
              }}
            >
              <Button type="primary" htmlType="submit">
                登录
              </Button>
            </Form.Item>
          </div>
        </div>
      </Form>
    </div>
  )
}

export default Login
